<template>
  <div class="custom-card right-card" @dblclick="editTag">
    <el-row v-for="(item, index) in curProps" :key="index" :span="24" class="card-item">
      <el-col :offset="1" :span="8" class="item-left">
        <span>{{ item.remark }}</span>
      </el-col>
      <el-col :span="10" class="item-right">
        <div>
          <span class="item-value" @click="getTagByKeyType(item)" @mouseenter="($e) => handleMouseEnter($e, item)"
            @mouseout="handleMouseOut(item)">{{ formatNumber(wellData[item.key]) }}</span><span class="item-unit">{{
              item.unit == "kg/m³" ? "" : item.unit
            }}</span>
        </div>
      </el-col>
      <el-col :span="5" class="item-date">{{ item.lastTime }}</el-col>
    </el-row>
    <el-dialog v-model="dialogVisible" :close-on-click-modal="false" draggable title="Settings" width="65%">
      <!-- <el-form :inline="true" :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="x">
          <el-input-number v-model="form.x"/>
        </el-form-item>
        <el-form-item label="y">
          <el-input-number v-model="form.y"/>
        </el-form-item>
      </el-form> -->
      <div style="width: 100%; text-align: right; margin-bottom: 4px">
        <el-button size="default" type="primary" @click="addRight">Add</el-button>
      </div>
      <el-table :data="tableData" border row-key="rowKey">
        <el-table-column align="center" label="No" type="index" width="50" />
        <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
          :width="item.width || ''" align="center">
          <template #default="scope">
            <!-- <el-select
              v-if="item.prop == 'keyType'"
              @change="tagitselfchange(scope.row)"
              v-model="scope.row.keyType"
              placeholder="please select"
              size="default"
              disabled 
            >
              <el-option label="Tag Type" value="1" />
              <el-option label="Tag Itself" value="2" />
            </el-select> -->
            <!-- <el-select
              v-if="item.prop == 'key' && scope.row.keyType == '1'"
              v-model="scope.row.key"
              filterable
              placeholder="please select"
            >
              <el-option
                v-for="item in tagTypesList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select> -->
            <!-- <el-select
              v-if="item.prop == 'key' && scope.row.keyType == '2'"
              v-model="scope.row.key"
              placeholder="please select"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              />
            </el-select> -->
            <div v-if="item.prop == 'key' && scope.row.keyType == '2'" class="input-with-button">
              <el-input v-model="scope.row.key" placeholder="Please Input" size="default" :clearable="false" disabled/>
              <el-button size="small" type="primary" @click="handleKeyButtonClick(scope.row)">
                Edit
              </el-button>
            </div>
            <el-input v-if="item.prop == 'remark'" v-model="scope.row.remark" placeholder="please input"
              size="default" />
            <el-input v-if="item.prop == 'unit'" v-model="scope.row.unit" placeholder="Please Input" size="default" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="Operator" width="100">
          <template #default="scope">
            <el-button size="default" text type="danger" @click="removeItem(scope.row.rowKey)">Delete</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="changeTag"> Confirm</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="newTagDialogVisible" title="Tag Configuration" width="45%" top="100px"
      :close-on-click-modal="false">
      <div class="tagConfigurationBox">
        <div class="left-box">
          <div>
            <div class="searchBar">
              <el-input placeholder="TagName Or Description" v-model="getAllTagPrarms.keyword"></el-input>
              <el-button type="primary" @click="getAllTagByKeywordFun">Search</el-button>
            </div>
            <div class="tip-box">Double Click Each Row to Add New Tag</div>
            <div class="left-list-box">
              <el-table :data="allTagNameList" border stripe :header-cell-style="{ 'text-align': 'center' }"
                height="100%" @row-dblclick="copyRowToRight">
                <el-table-column prop="tagName" show-overflow-tooltip label="TagName" align="left" width="300">
                </el-table-column>
                <el-table-column prop="unit" label="Unit" align="center" show-overflow-tooltip
                  width="100"></el-table-column>
                <el-table-column prop="remark" show-overflow-tooltip label="Description" align="left"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div class="page-box" style="padding-top: 0.5rem;">
        <custom-pagination style="text-align: left; justify-content: flex-start" :total="total" :page-count="pageCount"
          :current="currentPage" @pagination="handlePagination"></custom-pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CustomPagiation from "@/components/customPagiation.vue";
import { getAllTagByKeyword } from '@/api/index'
import { computed, onMounted, reactive, toRefs, watch } from "vue";
import * as d3 from "d3";
import { formatNumber, getCurrentDate } from "@/utils/common";
import { generateRandomKey } from "@/utils/dragresize";

export default {
  name: "CustomCard",
  components: { 'custom-pagination': CustomPagiation },
  props: ["rightProps", "data", "tagsList", "tagTypesList", "isEditting"],
  setup: (props, { emit }) => {
    let state = reactive({
      lastAddClickTime: new Date().getTime(),
      curProps: [],
      ttoredNames: '',
      total: 0,
      pageCount: 0,
      currentPage: 1,
      newTagDialogVisible: false,
      tableData: [],
      wellData: {},
      getAllTagPrarms: {
        keyword: "",
        page: 1,
        pageSize: 15
      },
      allTagNameList: [],
      columns: [
        { label: "Label", prop: "remark", width: "250" },
        // { label: "keyType", prop: "keyType", width: "" },
        { label: "TagName", prop: "key", width: '' },
        { label: "Unit", prop: "unit", width: "300" },
      ],
      dialogVisible: false,
      form: {
        x: 0,
        y: 0,
      },
    });
    state.curProps = props.rightProps || [];

    const editTag = () => {
      if (props.isEditting && !state.dialogVisible) {
        state.form.x = state.curProps[0].x;
        state.form.y = state.curProps[0].y;
        state.tableData = JSON.parse(JSON.stringify(state.curProps)).map(
          (item) => {
            item.rowKey = generateRandomKey(18);
            return item;
          }
        );
        console.log(state.tableData);
        state.dialogVisible = true;
      }
    };
    const changeTag = () => {
      state.curProps = JSON.parse(JSON.stringify(state.tableData));
      state.dialogVisible = false;
      d3.select("#right-card").style("left", `${state.form.x}px`);
      d3.select("#right-card").style("top", `${state.form.y}px`);
      emit("setCard", state.curProps);
    };
    const tagitselfchange = (row) => {
      if (row.keyType === "2") {
        row.key = "";
      } else if (row.keyType === "1") {
        row.key = "";
      }
    };
    const removeItem = (rowKey) => {
      state.tableData = state.tableData.filter(
        (item) => item.rowKey !== rowKey
      );
    };
    const handleKeyButtonClick = (row) => {
      let arr = JSON.parse(JSON.stringify(row));
      state.ttoredNames = arr.remark
      state.newTagDialogVisible = true;
      getAllTagByKeywordFun()
    }
    const getAllTagByKeywordFun = () => {
      getAllTagByKeyword(state.getAllTagPrarms).then(res => {
        if (res.code === 200) {
          state.total = res.data.total
          state.getAllTagPrarms.page = res.data.page
          state.getAllTagPrarms.pageSize = res.data.pageSize
          //state.storedConfigsData = res.data.records
          state.allTagNameList = res.data.records
          state.pageCount = res.data.pages
        } else {
          return this.$message.error(res.msg);
        }
      })
    }
    const handlePagination = (pagination) => {
      state.getAllTagPrarms.pageSize = pagination.pageSize
      state.getAllTagPrarms.page = pagination.page
      state.currentPage = pagination.page
      getAllTagByKeywordFun()
    }
    const copyRowToRight = (row) => {
      let arr = JSON.parse(JSON.stringify(row));
      for (const key in state.tableData) {
         if(state.tableData[key].remark == state.ttoredNames){
          state.tableData[key].key = arr.tagName
         }
      }
      state.newTagDialogVisible = false;
    }
    const addRight = () => {
      state.tableData.push({
        type: "rightcard",
        x: 100,
        y: 450,
        width: 100,
        height: 20,
        value: "",
        id: "",
        pid: "",
        keyType: "",
        key: "",
        unit: "",
        valueColor: "#ffffff",
        className: "",
        remark: "label",
        index: 1,
        rowKey: generateRandomKey(32),
      });
    };

    const getTagByKeyType = (tag) => {
      emit("getTagByKeyType", tag);
    };

    const handleMouseEnter = (e, tag) => {
      emit("handleMouseEnter", {
        dataItem: tag,
        event: e,
      });
    };

    const handleMouseOut = (tag) => {
      emit("handleMouseOut", tag);
    };

    const getHeight = computed(() => {
      let poHeight = 100 / state.curProps.length;
      return {
        height: `calc(${poHeight}%)`,
      };
    });
    onMounted(() => { });
    watch(
      () => props.data,
      (newValue, oldValue) => {
        state.wellData = { ...newValue };
      },
      { deep: true, immediate: true }
    );
    return {
      ...toRefs(state),
      editTag,
      removeItem,
      changeTag,
      addRight,
      tagitselfchange,
      getTagByKeyType,
      handleMouseEnter,
      getAllTagByKeywordFun,
      handleMouseOut,
      handlePagination,
      copyRowToRight,
      formatNumber,
      getCurrentDate,
      getHeight,
      handleKeyButtonClick
    };
  },
};
</script>

<style lang="scss">
.custom-card {
  color: #ffffff;
  padding: 10px;
  background: #132c51;

  .tip-box {
    text-align: left;
    height: 2rem;
    line-height: 2.2rem;
    color: red;
  }

  .tagConfigurationBox {

    display: flex;
    flex-direction: row;
    flex: 1;
    height: 60vh;

    .left-box {
      //border-right: 1px dotted #999;
      padding-right: 0.5rem;
      width: 100%;

      .left-list-box {
        display: flex;
        height: 53vh;
        //border: 1px solid #f00;
        overflow: auto;
      }

      .page-box {
        //height: 3vh;
      }

      .searchBar {
        display: flex;
        flex-direction: row;
        margin-bottom: 0.5rem
      }
    }

    .right-box {

      //border: 1px solid #f00;
      width: 68%;

      .operationBar {
        display: flex;
        justify-content: flex-end;
        flex-direction: row;
        margin-bottom: 0.5rem;

        .left-tip {
          line-height: 2rem
        }
      }

      .right-list-box {
        display: flex;
        height: 53vh;
        //border: 1px solid #f00;
        overflow: auto;

        .groupItem {
          display: inline-flex;
          border-radius: 4px;
          text-align: center;

          background: #dbedff;
          padding: 0.1rem 0.2rem;
          margin-right: 0.4rem;

          ::v-deep .el-radio-button__inner {
            padding: 0.2rem 0.3rem;
          }

          .axesName {
            display: inline-block;
            height: 1.2rem;
            align-items: center;
            padding: 0 0.1rem;
            margin: 0;
          }

        }

        .gapR {
          margin-right: 10px
        }
      }
    }
  }

  .input-with-button {
    display: flex;
    align-items: center;
    gap: 8px; // 输入框和按钮之间的间距
    width: 100%;

    .el-input {
      flex: 1; // 输入框占满剩余空间
    }
  }

  .card-item {
    margin-bottom: 5px;
    padding: 5px;
    background: #132c51;
    display: flex;
    align-items: center;
    border: 1px solid #14437a;
    align-items: center;
    z-index: 30 !important;
  }

  .item-left {
    font-size: 1.5vh;
    text-align: left;
  }

  .item-right {
    text-align: left;
    font-size: 1.5vh;
    padding-left: 10px;
  }

  .item-date {
    font-size: 1.2vh;
    align-content: center;
    color: #aab0b8;
  }

  .item-value {
    font-size: 1.5vh;
    display: inline-block;
    margin-right: 5px;
    text-align: right;
    font-family: "digital-7";
    font-weight: 600;
    color: aqua !important;
    cursor: pointer;
  }

  .item-unit {
    font-size: 1.5vh;
    display: inline-block;
    padding-top: 5px;
  }
}
</style>